package org.example.domain.order.service.mq_v2;


import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.domain.order.adapter.repository.IOrderRepository;
import org.example.domain.order.model.entity.OrderEntity;
import org.example.domain.transaction.model.entity.SucceedPayCallbackEntity;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

import static org.example.types.common.MQConstants.SUCCEED_PAY_CALLBACK_CONSUMER_GROUP;
import static org.example.types.common.MQConstants.SUCCEED_PAY_CALLBACK_TOPIC;
import static org.example.types.enums.ResponseCode.ORDER_DB_UPDATE_ERROR;

/**
 * @author yinghuashen
 * @version 1.0
 * @description:
 * @date 2025/3/14 22:26
 */

@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = SUCCEED_PAY_CALLBACK_CONSUMER_GROUP,
        topic = SUCCEED_PAY_CALLBACK_TOPIC,
        messageModel = MessageModel.CLUSTERING
)
public class SucceedPayCallBackTopicConsumer implements RocketMQListener<MessageExt> {

    @Resource
    private IOrderRepository orderRepository;

    @Override
    public void onMessage(MessageExt messageExt) {
        if(messageExt.getBody()==null){
            return;
        }
        SucceedPayCallbackEntity succeedPayCallbackEntity =
                JSONUtil.toBean(new String(messageExt.getBody(), StandardCharsets.UTF_8), SucceedPayCallbackEntity.class);
        try {
            String orderId = succeedPayCallbackEntity.getOrderId();
            log.info("SucceedPayCallBackTopicConsumer 收到支付成功回调消息：orderId = {}", orderId);

            int orderStatus = orderRepository.getOrderStatusById(orderId);

            if (orderStatus == OrderEntity.OrderStatus.PENDING_PAYMENT.getCode()) {
                if (!orderRepository.succeedPayOrder(orderId)) {
                    return;
                }
                log.info("SucceedPayCallBackTopicConsumer 订单 {} 支付成功", orderId);
            } else {
                log.warn("SucceedPayCallBackTopicConsumer 订单 {} 状态异常，无法变更为支付成功，需人工或外部退款处理", orderId);
                // TODO: 调用外部退款接口
            }
        } catch (AppException e) {
            throw new AppException(ORDER_DB_UPDATE_ERROR);
        }
    }
}
